import confg from './config';
const baseurl = confg.base_url + '/api/v1';
//添加finally：因为还有一个参数里面还有一个complete方法。
Promise.prototype.finally = function (callback) {
  let P = this.constructor;
  return this.then(
    value => P.resolve(callback()).then(() => value),
    reason => P.resolve(callback()).then(() => { throw reason })
  );
};

//封装异步api
const wxPromisify = fn => {
  return function (obj = {}) {
    return new Promise((resolve, reject) => {
      obj.success = function (res) {
        resolve(res)
      }
      obj.fail = function (res) {
        reject(res)
      }
      fn(obj)
    })
  }
}

const getLocation = wxPromisify(wx.getLocation);//获取经纬度
const showModal = wxPromisify(wx.showModal);//弹窗

// 封装post请求
const post = (url, data) => {
  return new Promise((resolve, reject) => {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    //网络请求
    wx.request({
      url: baseurl + url,
      data: data,
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'authorization': wx.getStorageSync('token_')
      },
      success: function (res) {//服务器返回数据
        if (res.statusCode == 200) {
          resolve(res.data);
        } else {//返回错误提示信息
          reject(res.data);
        }
        wx.hideLoading()
      },
      error: function (e) {
        wx.hideLoading()
        reject('网络出错');
      }
    })
  });
}
// 封装get请求
const get = (url, data) => {
  wx.showLoading({
    title: '加载中',
    mask: true
  })
  return new Promise((resolve, reject) => {
    //网络请求
    wx.request({
      url: baseurl + url,
      data: data,
      header: {
        'content-type': 'application/json',
        'authorization': wx.getStorageSync('token_')
      },
      success: function (res) {//服务器返回数据
        if (res.statusCode == 200) {
          resolve(res.data);
        } else {//返回错误提示信息
          reject(res.data);
        }
        wx.hideLoading();
      },
      error: function (e) {
        wx.hideLoading();
        reject('网络出错');
      }
    })
  });
}

module.exports = {
  post,
  get,
  getLocation,
  showModal
}